import React, { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Form, FormProps, Input, Modal } from 'antd';

import { store } from '@/store';

import { passwordValidator } from '@/config/rule';
import { securityPublicKey } from '@/services/base/denglumokuaidenglujiekou';
import { orgUserInfoUpdatePassword } from '@/services/base/yonghuguanliyonghumimaxiangguanjiekou';
import { encryptRSA } from '@/utils/encrypt';

import { BizObject } from '.';

export type EditPasswordRef = {
  open: (arg: { rowData: BizObject; onSuccess?: () => void }) => void;
};

export type EditPasswordProps = {};

const EditPassword: React.ForwardRefRenderFunction<EditPasswordRef, EditPasswordProps> = (
  { ...rest },
  ref
) => {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditPasswordRef['open']>[0]>();
  const submit = useRequest(
    async (query) => {
      // 加密密码
      const publicKey = (await securityPublicKey()).data;
      const encryptPassword = await encryptRSA(query.password, async () => publicKey);
      const encryptCheckPassword = await encryptRSA(query.checkPassword, async () => publicKey!);

      query.password = encryptPassword;
      query.checkPassword = encryptCheckPassword;

      await orgUserInfoUpdatePassword(
        {
          id: args?.rowData?.id as number,
          checkPassword: encryptCheckPassword,
          password: encryptPassword
        },
        {
          tupleResponse: false
        }
      );
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        form.setFieldsValue({});
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (query) => {
    await submit.runAsync(query);

    args?.onSuccess?.();
    setOpen(false);
    store.app?.message.success('操作成功');
  };

  const onClose = () => {
    if (submit.loading) {
      store.app?.message.error('请等待操作完成');

      return;
    }

    form.resetFields();
    setOpen(false);
  };

  return (
    <Modal
      title="修改密码"
      width={600}
      {...rest}
      okButtonProps={{
        disabled: submit.loading,
        loading: submit.loading
      }}
      cancelButtonProps={{
        disabled: submit.loading
      }}
      open={open}
      onCancel={onClose}
      onOk={() => {
        form.submit();
      }}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item
          label="当前登录用户密码"
          name="checkPassword"
          rules={[
            {
              required: true,
              message: '请输入当前登录用户密码'
            }
          ]}
        >
          <Input.Password placeholder="当前登录用户密码" />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码'
            },
            {
              validator: passwordValidator
            }
          ]}
          hasFeedback
        >
          <Input.Password placeholder="密码" />
        </Form.Item>

        <Form.Item
          label="确认密码"
          name="_password"
          dependencies={['password']}
          rules={[
            {
              required: true,
              message: '请输入确认密码'
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (value && value !== getFieldValue('password')) {
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                }
                return Promise.resolve();
              }
            })
          ]}
          hasFeedback
        >
          <Input.Password placeholder="确认密码" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default forwardRef(EditPassword);
